package cntv

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gregex"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/crawl/replayservice"
)

type Cntv struct {
	*core.AbstractCrawlReplayUrl
}

func (receiver *Cntv) CreateProgram(replayConfig *entity.CmsCrawlReplayConfig, manifestTask *entity.CmsCrawlReplayManifestTask) {
	//g.Dump(replayConfig)

	time := gtime.Now().Format("Ymd")
	url := fmt.Sprintf("%s&d=%s", replayConfig.SeedUrl, time)
	g.Log().Infof(gctx.GetInitCtx(), "大陆节目单爬虫开始 cntv start ->%v", url)
	match, _ := gregex.MatchString(`\?c=(.*)\&ser`, url)
	if len(match) < 2 {
		return
	}
	cKey := match[1]
	res := g.Client().GetContent(gctx.GetInitCtx(), url)
	list := g.NewVar(g.NewVar(res).Map()["data"]).Map()[cKey]
	//g.Dump(g.NewVar(list).Map()["list"])
	var ResList []*ListItem
	err := g.NewVar(g.NewVar(list).Map()["list"]).Structs(&ResList)
	if err != nil {
		g.Log().Warningf(gctx.GetInitCtx(), "cctv数据爬取出错->%v---url:%v", err, url)
		return
	}
	for i := 0; i < len(ResList); i++ {
		sTime := gtime.New(ResList[i].StartTime)
		eTime := gtime.New(ResList[i].EndTime)
		//g.Log().Infof(gctx.GetInitCtx(), "index:%v---sTime:%v--eTime:%v",i,sTime,eTime)
		programTask := new(entity.CmsCrawlReplayProgramTask)
		programTask.ManifestId = manifestTask.Id
		programTask.ConfigId = replayConfig.Id
		programTask.ProgramNo = g.NewVar(sTime.Unix()).String()
		programTask.ProgramName = ResList[i].Title
		programTask.ProgramStartTime = sTime
		programTask.ProgramEndTime = eTime
		programTask.CreateTime = gtime.Now()
		programTask.CrawlStatus = replayservice.ProgramTaskInit
		programTask.HostIp = replayConfig.Host
		replayservice.CheckAndSave(programTask)
	}

}

type ListItem struct {
	Title     string `json:"title"`
	StartTime string `json:"startTime"`
	EndTime   string `json:"endTime"`
}
